package converters::strings;

use Fcntl ':flock';
use Data::Dumper;

# The file could be a filename or a reference [to scalar
# containing the contents of the file].

sub new {
my $class=shift;
my $file=shift;

	my $self={};
	if(!defined($file)) {
		return undef;
	}
	if(ref($file)) {
		$self->{reference}=$file;
	} elsif(! -f $file || ! -r $file) {
		return undef;
	} else {
		$self->{file}=$file;
	}
	bless($self);
	$self->{type}="strings";
	return $self;
}

sub convert {
my $self=shift;
my ($wfd,$fd);

	my $buff;
	if(exists($self->{file})) {
		open($fd,$self->{file});
		return -1 if !defined($fd);

		# We have exclusive lock, so open results file
		my $fname=$self->{file} . ".txt." . $self->{type};
		open($wfd,">>$fname");
		if(! defined($wfd)) {
			close($fd);
			return -3;
		}
		# Attempt exclusive lock
		if(! flock($wfd,LOCK_EX|LOCK_NB)) {
			return -2;
		}

		while(read($fd,$buff,1024)) {
			while(1) {
				if($buff =~ /((\w+[\.\s]+){3,})/) {
					my $x=$1; my $y=$x; chomp $x;
					print $wfd "$x\n";
					$buff =~ s/$y//g;
				} else {
					last;
				}
			}
		}
		close($fd);
		close($wfd);
		$self->{converted_file}=$fname;
		$self->{converted_fd}=undef;
	} else {
		# If we get there we have a self->{reference}
		# containing the string we wish to convert...
		my @strings=split(/\n/,${$self->{reference}});
		$self->{converted_strings}=[];
		for my $bbb (@strings) {
			my $buff=$bbb;
			while(1) {
				if($buff =~ /([:\_\w\d\.\s\!\"\'\#\$\%\^\&\*\(\)\=\-\+\[\]\{\}\@\'\~\<\>\,\?\/]+)/) {
					my $x=$1; my $y=$x;
					if(length($x)>=5) {
						push @{$self->{converted_strings}},$x;
					}
					my $y=length($x);
					my $z=index($buff,$x);
					if($z>-1) {
						if($z>0) {
							$buff=substr($buff,0,$z-1) . substr($buff,$z+$y);
						} else {
							$buff=substr($buff,$z+$y);
						}
					}
					next;
				}
				last;
			}
		}
		$self->{converted_strings_line}=0;
	}
	return 1;
}

sub start_converted_read {
my $self=shift;

	if(exists($self->{converted_file})) {
		my $fd;
		open($fd,$self->{converted_file});
		$self->{converted_fd}=$fd;
	} else {
		$self->{converted_strings_line}=0;
	}
}

sub stop_converted_read {
my $self=shift;

	if(exists($self->{converted_file})) {
		if(defined($self->{converted_fd})) {
			close($self->{converted_fd});
			$self->{converted_fd}=undef;
		}
	} else {
		$self->{converted_strings_line}=0;
	}
}

sub get_converted_line {
my $self=shift;

	if(exists($self->{converted_file})) {
		if(defined($self->{converted_fd})) {
			my $fd=$self->{converted_fd};
			my $cline=<$fd>;
			return(undef) if !defined($cline);
			chomp $cline;
			return $cline;
		}
		return undef;
	} else {
		if($self->{converted_strings_line} <
			scalar(@{$self->{converted_strings}})) {
			my $x=$self->{converted_strings_line}++;
			return $self->{converted_strings}->[$x];
		} else {
			return undef;
		}
	}
}

1;

